package com.example.demo.RpcDemo;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @projectName: 接口梳理
 * @package: com.midea.oms.Demo.RpcDemo
 * @className: MyHandler
 * @author: zhangcan30
 * @description: TODO
 * @date: 2024/3/27 11:19
 * @version: 1.0
 */
public class MyHandler extends TextWebSocketHandler {

    private Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
    private Map<String, String> usernames = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("WebSocket connection opened: " + session.getId());
        String username = "user" + (sessions.size() + 1);
        sessions.put(username, session);
        usernames.put(session.getId(), username);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("Received message: " + message.getPayload());

        // 解析消息中的目标客户端标识符和消息内容
        String[] parts = message.getPayload().split(":", 2);
        String targetUsername = parts[0];
        String content = parts[1];

        // 查找目标客户端并发送消息
        WebSocketSession targetSession = sessions.get(targetUsername);
        if (targetSession != null) {
            targetSession.sendMessage(new TextMessage(usernames.get(session.getId()) + ": " + content));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("WebSocket connection closed: ");
        String username = usernames.remove(session.getId());
        sessions.remove(username);
    }
}
